<template>
  <div class="playlist-drawer" :class="{ 'is-open': playListDetails.isOpen }">
    <div class="playlist-mask" @click="closeDrawer"></div>
    <div class="playlist-content">
      <div class="playlist-container">
        <div class="header-background" :style="headerStyle"></div>
        <button class="close-button" @click="closeDrawer">×</button>
        <header class="playlist-header">
          <div class="header-content">
            <div class="cover-image">
              <img :src="`${config.downloadUrl}?name=${playlist.pic}`" alt="歌单封面">
            </div>
            <div class="playlist-info">
              <h1>{{ playlist.title }}</h1>
              <div class="creator-info">
                by:{{ playlist.creater }}
              </div>
              <div class="tags">
                标签:
                <span class="tag">{{ playlist.style }}</span>
              </div>
              <p class="description">{{ playlist.introduction }}</p>
              <div class="actions">
                <button class="play-all" @click="playAll">
                   播放全部
                </button>
                <button class="favorite" @click="toggleFavorite">
                  {{ isFavorite ? '★' : '⭐' }} 收藏歌单
                </button>
              </div>
            </div>
          </div>
        </header>

        <table class="song-list">
          <thead>
            <tr>
              <th style="color: black;" v-for="header in tableHeaders" :key="header">{{ header }}</th>
            </tr>
          </thead>
          <tbody>
            <tr v-for="(song,index) in listSongStore.SongData" :key="index" @dblclick="audioMixin.methods.toPlay(song.id, song.url, song.pic, song.name, song.singerId, song.lyric, index)">
              <td><img class="song-pic" :src="`${config.downloadUrl}?name=${song.pic}`"></td>
              <td>{{ song.name }}</td>
              <td @click.stop="toSingerDetails(song.singerId)" 
                  class="singer-name">{{ singerNames[song.singerId] || song.singerId }}</td>
              <td>{{ song.introduction }}</td>  
            </tr>
          </tbody>
        </table>
      </div>
    </div>
  </div>
</template>

<script setup name="playListDetails">
import { ref, reactive, onMounted, computed } from 'vue'
import { usePlayListDetails } from '@/store/playListDetails'
import { selectSongListById } from '@/api/songList';
import { useListSongStore } from '@/store/listSong';
import { selectSongBySongListIdNoPage } from '@/api/listSong';
import { selectSongById } from '@/api/song';
import { audioMixin } from '@/mixins';
import { useAudioStore } from '@/store/audio';
import config from '../../public/config';
import { getSingerById } from '@/api/singer';
import { useSingerStore } from '@/store/singer';
const playListDetails = usePlayListDetails()
const listSongStore = useListSongStore()
const audioStore = useAudioStore()
const singerStore = useSingerStore()
defineOptions({
    mixins: [audioMixin],
});

// 播放列表基本信息
const playlist = reactive({
  title: '',
  creater: '',
  style:'' ,
  introduction: '',
  pic: ''
})

// 表格头部
const tableHeaders = ['音乐封面','音乐标题','歌手','专辑']

// 收藏状态
const isFavorite = ref(false)

// 添加主题色状态
const dominantColor = ref('rgba(0, 0, 0, 0.1)')

// 计算头部样式
const headerStyle = computed(() => ({
  backgroundColor: dominantColor.value,
  backgroundImage: `url(${config.downloadUrl}?name=${playlist.pic})`,
}))

// 提取图片主题色的函数
const extractDominantColor = async (imageUrl) => {
  return new Promise((resolve) => {
    const img = new Image()
    img.crossOrigin = 'Anonymous'
    img.src = imageUrl
    
    img.onload = () => {
      const canvas = document.createElement('canvas')
      const ctx = canvas.getContext('2d')
      canvas.width = img.width
      canvas.height = img.height
      
      ctx.drawImage(img, 0, 0)
      const imageData = ctx.getImageData(0, 0, canvas.width, canvas.height).data
      
      let r = 0, g = 0, b = 0, count = 0
      
      for (let i = 0; i < imageData.length; i += 4) {
        r += imageData[i]
        g += imageData[i + 1]
        b += imageData[i + 2]
        count++
      }
      
      r = Math.floor(r / count)
      g = Math.floor(g / count)
      b = Math.floor(b / count)
      
      resolve(`rgba(${r}, ${g}, ${b}, 0.8)`)
    }
  })
}

// 播放全部方法
const playAll = () => {
   audioStore.listOfSong = listSongStore.SongData
   audioStore.id = audioStore.listOfSong[0].id;
    audioStore.url = audioStore.listOfSong[0].url;
    audioStore.pic = audioStore.listOfSong[0].pic
    audioStore.title = audioStore.listOfSong[0].name
    audioStore.listIndex = 0
    audioStore.singerId = audioStore.listOfSong[0].singerId
    audioStore.lyric = audioStore.listOfSong[0].lyric
}

const toggleFavorite = () => {
  isFavorite.value = !isFavorite.value
  console.log(isFavorite.value ? '收藏成功' : '取消收藏')
}


// 添加关闭抽屉方法
const closeDrawer = () => {
  playListDetails.isOpen = false
}


onMounted(() => {
  getSongListDetails()
  getSongList()
})

async function getSongList() {
  let params = new URLSearchParams();
  params.append('id', playListDetails.detailsId);
  await selectSongListById(params)
    .then(async res => {
      playlist.title = res.title
      playlist.creater = res.creater
      playlist.style = res.style
      playlist.introduction = res.introduction
      playlist.pic = res.pic
      
      // 提取图片主题色
      const imageUrl = `${config.downloadUrl}?name=${res.pic}`
      dominantColor.value = await extractDominantColor(imageUrl)
    })
}

async function getSongListDetails() {
  let params = new URLSearchParams();
  params.append('songListId', playListDetails.detailsId);
  try {
    const res = await selectSongBySongListIdNoPage(params);
    listSongStore.songIds = res.map(item => item.songId);
    listSongStore.SongData = []
    // 在获取到 songIds 后立即调用 getSongDetails
    await getSongDetails();
  } catch (error) {
    console.error('获取歌曲列表失败:', error);
  }
}

// 添加响应式数据存储歌手名称
const singerNames = ref({})

// 添加获取歌手名称的方法
async function getSingerName(singerId) {
  const params = new URLSearchParams();
  params.append('id', singerId);
  try {
    const res = await getSingerById(params);
    singerNames.value[singerId] = res.name;
  } catch (error) {
    console.error('获取歌手信息失败:', error);
  }
}

// 修改 getSongDetails 方法
async function getSongDetails() {
  if (listSongStore.songIds.length === 0) {
    return;
  }
  const requests = listSongStore.songIds.map(songId => {
    const params = new URLSearchParams();
    params.append('id', songId);
    return selectSongById(params);
  });
  try {
    const results = await Promise.all(requests);
    listSongStore.SongData = results;
    
    // 获取所有歌手的名称
    const singerRequests = results.map(song => getSingerName(song.singerId));
    await Promise.all(singerRequests);
  } catch (error) {
    console.error('请求出错:', error);
  }
}
function toSingerDetails(singerId) {
  singerStore.singerId = singerId
  singerStore.isSingerOpen = true
}
</script>

<style scoped>
.playlist-drawer {
  position: fixed;
  top: 0;
  right: 0;
  bottom: 0;
  width: 100%;
  visibility: hidden;
  z-index: 1000;
  transition: visibility 0.3s ease;
}

.playlist-mask {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.5);
  opacity: 0;
  transition: opacity 0.3s cubic-bezier(0.4, 0, 0.2, 1);
}

.playlist-content {
  position: absolute;
  top: 0;
  bottom: 0;
  left: 0;
  right: 0;
  height: 100vh;
  width: 100%;
  background: #fff;
  transform: translateY(100%);
  transition: transform 0.3s cubic-bezier(0.4, 0, 0.2, 1);
  overflow-y: overlay;
}

.playlist-drawer.is-open {
  visibility: visible;
  transition-delay: 0.3s;
}

.playlist-drawer:not(.is-open) {
  transition-delay: 0.3s;
}

.playlist-drawer.is-open .playlist-mask {
  opacity: 1;
}

.playlist-drawer.is-open .playlist-content {
  transform: translateY(0);
}

/* 原有的样式修改 */
.playlist-container {
  position: relative;
  z-index: 1;
  max-width: none;
  margin: 0;
  padding: 20px;
  height: 100%;
  box-sizing: border-box;
  padding-right: 24px;
}

.header-background {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  height: 400px; /* 调整背景高度 */
  background-size: cover;
  background-position: center;
  filter: blur(30px);
  opacity: 0.6;
  z-index: -1;
}

.playlist-header {
  position: relative;
  padding: 40px 20px;
  margin-bottom: 30px;
  color: #fff;
}

.header-content {
  display: flex;
  gap: 30px;
  align-items: flex-start;
}

.cover-image {
  flex-shrink: 0;
  width: 200px;
  height: 200px;
  border-radius: 12px;
  overflow: hidden;
  box-shadow: 0 8px 24px rgba(0, 0, 0, 0.2);
}

.playlist-info {
  flex: 1;
  min-width: 0; /* 防止子元素溢出 */
  text-align: left;
}

.playlist-info h1 {
  margin: 0 0 16px 0;
  font-size: 24px;
  color: #fff;
  text-shadow: 0 2px 4px rgba(0, 0, 0, 0.3);
}

.creator-info {
  margin-bottom: 12px;
  color: rgba(255, 255, 255, 0.9);
  text-shadow: 0 1px 2px rgba(0, 0, 0, 0.2);
}

.tags {
  margin-bottom: 12px;
  color: rgba(255, 255, 255, 0.9);
}

.tag {
  display: inline-block;
  padding: 4px 12px;
  margin-left: 8px;
  background: rgba(255, 255, 255, 0.2);
  border-radius: 15px;
  font-size: 14px;
}

.description {
  margin: 16px 0;
  line-height: 1.6;
  color: rgba(255, 255, 255, 0.9);
  text-shadow: 0 1px 2px rgba(0, 0, 0, 0.2);
  /* 处理过长的文本 */
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-line-clamp: 3;
  line-clamp: 3;
  -webkit-box-orient: vertical;
}

.actions {
  margin-top: 20px;
  display: flex;
  gap: 12px;
}

.actions button {
  padding: 8px 24px;
  border: none;
  border-radius: 20px;
  cursor: pointer;
  font-size: 14px;
  transition: all 0.3s ease;
}

.play-all {
  background: #1890ff;
  color: white;
}

.play-all:hover {
  background: #40a9ff;
}

.favorite {
  background: rgba(255, 255, 255, 0.2);
  color: #fff;
}

.favorite:hover {
  background: rgba(255, 255, 255, 0.3);
}

.song-list {
  width: 100%;
  border-collapse: collapse;
  margin-right: -16px;
  padding-right: 16px;
}

.song-list th,
.song-list td {
  padding: 12px;
  text-align: left;
  border-bottom: 1px solid #f0f0f0;
}

.song-list th {
  font-weight: normal;
  color: #999;
}

.song-list tr:hover {
  background: #f5f5f5;
}

/* 新增关闭按钮样式 */
.close-button {
  position: absolute;
  right: 20px;
  top: 20px;
  width: 32px;
  height: 32px;
  border: none;
  background: none;
  font-size: 24px;
  cursor: pointer;
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 50%;
  color: #fff;
  z-index: 3;
}

.close-button:hover {
  background: rgba(255, 255, 255, 0.2);
}

.playlist-enter-active,
.playlist-leave-active {
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
}

.playlist-enter-from,
.playlist-leave-to {
  transform: translateY(100%);
  opacity: 0;
}

.playlist-enter-to,
.playlist-leave-from {
  transform: translateY(0);
  opacity: 1;
}

.song-pic {
  width: 50px;
  height: 50px;
  border-radius: 10px;
}

.cover-image {
  position: relative;
  z-index: 2;
  width: 200px;
  height: 200px;
  margin-bottom: 20px;
  border-radius: 12px;
  overflow: hidden;
  box-shadow: 0 8px 24px rgba(0, 0, 0, 0.2);
}

.cover-image img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

/* 自定义滚动条样式 */
.playlist-content {
  /* 修改现有样式 */
  overflow-y: overlay; /* 改为 overlay 使滚动条悬浮在内容上 */
}

.playlist-content::-webkit-scrollbar {
  width: 8px; /* 滚动条宽度 */
}

.playlist-content::-webkit-scrollbar-track {
  background: transparent; /* 轨道背景透明 */
}

.playlist-content::-webkit-scrollbar-thumb {
  background-color: rgba(255, 255, 255, 0.3); /* 滚动条颜色 */
  border-radius: 4px; /* 圆角 */
  transition: background-color 0.3s;
}

/* 鼠标悬浮时的滚动条样式 */
.playlist-content::-webkit-scrollbar-thumb:hover {
  background-color: rgba(255, 255, 255, 0.5);
}

/* 适配 Firefox */
.playlist-content {
  scrollbar-width: thin;
  scrollbar-color: rgba(255, 255, 255, 0.3) transparent;
}

/* 确保内容区域有足够的右边距，避免被滚动条遮挡 */
.playlist-container {
  padding-right: 24px; /* 增加右侧内边距 */
}

/* 优化表格区域的滚动条 */
.song-list {
  margin-right: -16px; /* 抵消父容器的右边距 */
  padding-right: 16px;
}

.singer-name {
  cursor: pointer;
}

.singer-name:hover {
  text-decoration: underline;
  color: #1890ff;  /* 可选：悬停时改变文字颜色 */
}
</style>